//
//  OtherCatViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/29.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "OtherCatViewController.h"
//获取数据类
#import "PagingData.h"
#import "GetPagingDataList.h"
//管理图片
#import "PicCatViewController.h"
#import "FriendlyLinkCell.h"





@interface OtherCatViewController ()<UITableViewDelegate,UITableViewDataSource,PagingDataListServiceDelegate,ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UITableView *_tableView;
    GetPagingDataList *DataService;
    
    ASIFormDataRequest *deleteRequest;
    NSString *action;
    NSDictionary  *paramsDict;
    NSInteger selectRow;
}

@end

@implementation OtherCatViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIScreen *screen = [UIScreen mainScreen];
    self.view.frame = CGRectMake(0, 0, screen.bounds.size.width, screen.bounds.size.height - 64 - 35);
    _tableView.frame = self.view.frame;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 80;
    //获取数据
    [self getDate];
    // 集成刷新控件
    [self setupRefresh];
    [_tableView headerBeginRefreshing];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark TableViewDelegate Methods

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"LinkCell";
    FriendlyLinkCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = (FriendlyLinkCell *)[[NSBundle mainBundle]loadNibNamed:@"FriendlyLinkCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UIImageView *img =(UIImageView *)[cell.contentView viewWithTag:1];
    //img.image = [UIImage imageNamed:@"u12.png"];
    [img sd_setImageWithURL:DataService.pageInfo.dataArr[row][@"picturePath"] placeholderImage:PLACE_HODER_IMG];
    img.contentMode = UIViewContentModeScaleAspectFit;
    //[img imgWithUrl:DataService.pageInfo.dataArr[row][@"picture"]];
    //图片地址
    //NSString *str = [ substringToIndex:9];
    UILabel *name = (UILabel *)[cell.contentView viewWithTag:2];
    name.text = DataService.pageInfo.dataArr[row][@"pictureLink"];
    if (name.text.length == 0) {
        name.text = @"暂无链接";
    }
    //修改
    UIButton *alter = (UIButton *)[cell.contentView viewWithTag:4];
    [alter addTarget:self action:@selector(alter:) forControlEvents:UIControlEventTouchUpInside];
    alter.tag = indexPath.row + 10;
    //删除
    UIButton *delete = (UIButton *)[cell.contentView viewWithTag:5];
    [delete addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
    delete.tag = indexPath.row + 10;
    return cell;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (DataService.pageInfo.dataArr.count != 0) {
        return DataService.pageInfo.dataArr.count;
    }else{
        return 0;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//获取数据
-(void)getDate{
    DataService = [[GetPagingDataList alloc]initWithAction:@"Advertisementlist" Kind:@"uid"];
    //linkarr = linkService.pageInfo.dataArr;
    DataService.delegate = self;
}

#pragma mark 刷新

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (DataService.isQuery ||![Constants isExistenceNetwork]) {
        [_tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    DataService.pageInfo.pageno = @"1";
    [DataService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (DataService.isQuery || !DataService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        DataService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [DataService.pageInfo nextPage];
    [DataService pageQuery];
}
#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}

-(void)refreshTableView{
    [_tableView headerBeginRefreshing];
}

#pragma IBAction Method

-(void)alter:(id)sender{
    UIButton *btn = sender;
    NSInteger row = btn.tag - 10;
    NSLog(@"%@",DataService.pageInfo.dataArr[row][@"id"]);
    PicCatViewController *PCVC = [[PicCatViewController alloc]initWithNibName:@"PicCatViewController" bundle:nil];
    //设置属性
    PCVC.picId = DataService.pageInfo.dataArr[row][@"id"];
    PCVC.state = @"alterAd";
    [_delegate push:PCVC];
}
-(void)delete:(id)sender{
    UIButton *btn = sender;
    selectRow = btn.tag - 10;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
#pragma mark - UIAlertViewDelegate
//删除处理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            deleteRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
            deleteRequest.requestMethod = @"POST";
            // 设置超时时间
            deleteRequest.timeOutSeconds = 30;
            deleteRequest.delegate = self;
            // 设置参数
            action = @"Advertisementdel";
            paramsDict =  @{@"uid":UNAME,@"id":DataService.pageInfo.dataArr[selectRow][@"id"]};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR,action,paramsStr];
            NSData *paramsData = [result toGBKEncodingData];
            deleteRequest.postBody = [paramsData mutableCopy];
            
            [deleteRequest startAsynchronous];
        }
    }
}

#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            [DataService.pageInfo.dataArr removeObjectAtIndex:selectRow];
            //删除单元格的某一行时，在用动画效果实现删除过程
            [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:selectRow inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [_tableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

//删除请求
-(void)postDelRequest{
    
}

-(void)dealloc{
    DataService = nil;
}

@end
